<?php

require_once __DIR__ . '/../../../vendor/autoload.php';

use JLPay\Core\OrgConfig;
use JLPay\Core\DemoConfig;
use JLPay\Services\Trans\Common\GetOpenidService;
use JLPay\Models\Trans\Common\GetOpenidRequest;
use JLPay\Models\Trans\Common\GetOpenidResponse;
use JLPay\Utils\Logger;
use JLPay\Utils\DemoRequestHandler;

/**
 * 交易 - Common获取OpenID功能使用示例
 */

// =================== 工具函数 =====================
/**
 * 创建配置对象
 */
function createConfig(): OrgConfig
{
    return DemoConfig::createConfig();
}

// =================== 数据构建函数 =====================
/**
 * 构建获取OpenID请求
 */
function buildGetOpenidRequest(): GetOpenidRequest
{
    $request = new GetOpenidRequest();
    
    // 设置请求参数
    $request->setMchId("849584358120018");
    $request->setPayType("wxpay");
    $request->setAuthCode("131208648101095993");
    $request->setSubAppid("wxid_129752pfasf1671");
    $request->setAppUpIdentifier("com.example.app");
    $request->setDeviceInfo("N50007A8890");
    $request->setMchCreateIp("123.12.12.123");
    
    return $request;
}

// =================== 示例函数 =====================
/**
 * 获取OpenID示例
 */
function getOpenidDemo(): void
{
    $logger = Logger::getInstance();
    $logger->info("开始执行获取OpenID示例");
    
    // 创建配置对象和获取OpenID服务
    $config = createConfig();
    $getOpenidService = new GetOpenidService($config);
    
    // 创建获取OpenID请求
    $request = buildGetOpenidRequest();
    
    // 发送请求 - 使用DemoRequestHandler
    $response = DemoRequestHandler::sendRequestAndHandleResponse(
        $getOpenidService, 
        $request, 
        "获取OpenID",
        function($service, $request) {
            return $service->getOpenid($request);
        }
    );
    
    // 处理响应结果
    if ($response && $response->isSuccess()) {
        $logger->info("响应报文：" . json_encode($response->toArray(), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
    }
    
    $logger->info("获取OpenID示例执行完毕");
}

// =================== 主程序 =====================
$logger = Logger::getInstance();

$logger->info("=" . str_repeat("=", 50));
$logger->info("===== 获取OpenID示例 开始 =====");
$logger->info("=" . str_repeat("=", 50));

getOpenidDemo();

$logger->info("=" . str_repeat("=", 50));
$logger->info("===== 获取OpenID示例执行完毕 =====");
$logger->info("=" . str_repeat("=", 50)); 